package com.lingxu.base.common.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;

public class HttpApiUtil {

    public static String getContentByPost(HttpClient client, String url, String body) {
        String content = null;
        PostMethod method = new PostMethod(url);
        method.setRequestBody(body);// addParameters(postData);
        try {
            method.setRequestHeader("Content-Type", "application/json");
            method.setRequestHeader("Accept-Encoding", "gzip, deflate");
            method.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.9");

            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + method.getStatusLine());
            }
            byte[] responseBody = method.getResponseBody();
            content = new String(responseBody, "utf-8");
            System.out.println(content);

        }
        catch (HttpException e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        }
        catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        }
        finally {
            method.releaseConnection();
        }

        return content;
    }

}
